<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Scripts extends CI_Controller {

    public function index() {
        echo "It works.";
    }

    public function order() {
        $user_id = $this->input->post("uid");
        $meal_id = $this->input->post("meal_id");
        $comment = $this->input->post("comment");

        if ($user_id == null || $meal_id == null) {
            echo "Invalid POST data";
            return;
        }
        
        if ($comment == null){
            $comment = " ";
        }
        
        $user_id = intval($user_id);
        $meal_id = intval($meal_id);

        //Load all the things
        $this->load->model("user_orders");
        $this->load->model("mealtimes");

        //Get's tonights meals
        $tonightsMeals = $this->mealtimes->getMealsYMD(date("Y"), date("m"), date("j"));

        $orderable = $tonightsMeals->row()->mealtime_orderable;
        $cutoff = date("H:i:s", strtotime($tonightsMeals->row()->mealtime_cutoff));
        $currentTime = date("H:i:s", time());

        if ($orderable == 1 && $currentTime < $cutoff) {
            //Allow the user to continue   

            $allergies = $this->checkForAllergies($user_id, $meal_id);

            if (empty($allergies)) {
                if ($this->user_orders->order($user_id, $meal_id, filter_profanity($comment))) {
                    //Success
                    echo "good";
                } else {
                    //Failure
                    echo "There was an error server side.";
                }
            } else {
                //Tell the user that they have allergies
                // Load XML writer library
                $this->load->library('Xml_writer');
                // Initiate class
                $xml = new Xml_writer;
                $xml->setRootName('data');
                $xml->initiate();

                foreach ($allergies as $id => $name) {
                    $xml->startBranch('allergy');
                    $xml->addNode('name', $name);
                    $xml->addNode('id', $id);
                    $xml->endBranch();
                }

                // Print the XML to screen
                $xml->getXml(true);
            }
        } else {
            //Send notification to user stating that they're past the cutoff period
            echo "Past the cut-off time for meal ordering.";
        }
    }

    public function overrideOrder() {
        $user_id = $this->input->post("uid");
        $meal_id = $this->input->post("meal_id");
        $comment = $this->input->post("comment");

        $this->load->model("user_orders");

        if ($this->user_orders->order($user_id, $meal_id, filter_profanity($comment))) {
            echo "good";
        } else {
            echo "Internal server database error when ordering";
        }
    }
    
    public function vote() {
        $user_id = $this->input->post("uid");
        $mtm_id = $this->input->post("meal_id");

        if ($user_id == null || $mtm_id == null) {
            echo "Invalid POST data";
            return;
        }

        //Load all the things!
        $this->load->model("mealtimes");
        $this->load->model("user_votes");

        //Get's tonights meals
        $tonightsMeals = $this->mealtimes->getMealsYMD(date("Y"), date("m"), date("j"));

        $servetime = date("H:i:s", strtotime($tonightsMeals->row()->mealtime_servetime)); 
        $currentTime = date("H:i:s", time());

        if ($currentTime < $servetime) { //Temp removal
            //Allow the user to continue            
            $allergies = $this->checkForAllergies($user_id, $mtm_id);

            if (empty($allergies)) {
                //Check user voted
                if ($this->user_votes->vote($user_id, $tonightsMeals, $mtm_id)) {
                    echo "good";
                } else {
                    echo "Internal server database error when voting";
                }
            } else {
                //Tell the user that they have allergies
                // Load XML writer library
                $this->load->library('Xml_writer');
                // Initiate class
                $xml = new Xml_writer;
                $xml->setRootName('data');
                $xml->initiate();

                foreach ($allergies as $id => $name) {
                    $xml->startBranch('allergy');
                    $xml->addNode('name', $name);
                    $xml->addNode('id', $id);
                    $xml->endBranch();
                }

                // Print the XML to screen
                $xml->getXml(true);
            }
        } else {
            //Send notification to user stating that they're past the cutoff period
            echo "Past the cut-off time for meal voting.";
        }
    }

    public function overrideVote() {
        //This funciton will be called by the device if they still wish to vote
        //on a meal even though they have triggered allergies.

        $user_id = $this->input->post("uid");
        $mtm_id = $this->input->post("meal_id");

        if ($user_id == null || $mtm_id == null) {
            echo "Invalid POST data";
            return;
        }

        $this->load->model("mealtimes");
        $this->load->model("user_votes");

        $tonightsMeals = $this->mealtimes->getMealsYMD(date("Y"), date("m"), date("j"));

        if ($this->user_votes->vote($user_id, $tonightsMeals, $mtm_id)) {
            echo "good";
        } else {
            echo "Internal server database error when voting";
        }
    }

    public function futureMeals() {
        $this->load->model('mealtimes');
        $this->load->model('defaults');
        $this->load->library('Xml_writer');

        $xml = new Xml_writer;
        $xml->setRootName('data');
        $xml->initiate();


        for ($i = 1; $i <= $this->defaults->getFutureCount(); $i++) {
            $currentDay = strtotime("+$i day");

            $xml->startBranch('day');
            $xml->addNode('date', date('D (jS M, Y)', $currentDay));

            $year = date('Y', $currentDay);
            $month = date('n', $currentDay);
            $day = date('j', $currentDay);

            $meals = $this->mealtimes->getMealsYMD($year, $month, $day);

            foreach ($meals->result() as $result) {
                $xml->startBranch('meal');

                $xml->addNode('id', $result->mealtime_meals_id);
                $xml->addNode('name', $result->meal_title);
                $xml->addNode('description', $result->meal_description);

                $xml->endBranch();
            }

            $xml->endBranch();
        }

        $xml->getXml(true);
    }

    /*
     * Function returns true if there are no allergies
     */

    private function checkForAllergies($user_id, $mealtime_meals_id) {
        //Select the allergies for the current user

        $this->load->model('mealtime_meals');
        $this->load->model('meals');

        $meal_id = $this->mealtime_meals->getMealID($mealtime_meals_id);

        if ($meal_id < 0) {
            return null;
        }

        $mealBasetypes = $this->meals->getBasetypes($meal_id);

        $mbArray = array();
        foreach ($mealBasetypes->result() as $result) {
            $mbArray[] = $result->basetype_id;
        }


        $this->load->model('users');
        $userBasetypes = $this->users->getBasetypes($user_id);

        $ubArray = array();
        if ($userBasetypes != null) {
            foreach ($userBasetypes->result() as $result) {
                if (in_array($result->basetype_id, $mbArray)) {
                    $ubArray[$result->basetype_id] = $result->basetype_title;
                }
            }
        }

        return $ubArray;
    }

    public function getAllergies() {

        $user_id = $this->input->post("user_id");

        $this->load->library('Xml_writer');
        $this->load->model('users');
        $this->load->model('basetypes');

        $allergies = $this->users->getBasetypes($user_id);
        $aArray = array();

        if ($allergies != null) {
            foreach ($allergies->result() as $result) {
                $aArray[] = $result->basetype_id;
            }
        }

        $basetypes = $this->basetypes->getAll();

        $xml = new Xml_writer;
        $xml->setRootName('data');
        $xml->initiate();

        foreach ($basetypes->result() as $result) {
            $xml->startBranch('allergy');

            $xml->addNode('id', $result->basetype_id);
            $xml->addNode('name', $result->basetype_title);

            if (in_array($result->basetype_id, $aArray)) {
                $xml->addNode('selected', 1);
            } else {
                $xml->addNode('selected', 0);
            }

            $xml->endBranch();
        }

        $xml->getXml(true);
    }

    public function saveAllergies() {
        $this->load->model('users');

        $allergies = $this->input->post('allergies');
        $user_id = $this->input->post('user_id');

        if ($user_id == null) {
            echo "Invalid POST data";
            return;
        }

        if ($allergies == null) {
            //Delete all allergies corresponding to a user
            if ($this->users->deleteAllRequirements($user_id)) {
                echo "good";
            } else {
                echo "Internal server error when updating meals";
            }
            return;
        }

        if ($this->users->updateBasetypes($user_id, $allergies)) {
            echo "good";
        } else {
            echo "Internal server error when updating meals";
        }
    }
    
    public function login(){
        $this->load->model('users');
        $username = $this->input->post('user');
        $password = $this->input->post('pass');
        
        $password = $password;//encrypt at later stage
        
        $user = $this->users->authenticate($username,$password);
        
        if ($user){
            echo $user->user_id;
        }
        else{
            echo '0';
        }
    }
    
    public function toggleNotifications(){
        $user_id = $this->input->post('uid');
        $dev_token = $this->input->post('devtoken');
        $notifiable = $this->input->post('notifiable');
        
        if ($user_id == null || $dev_token == null || $notifiable == null){
            echo "Null inputs"; // Test output
            return;
        }

        $this->load->model('user_devices');
        
        if ($this->user_devices->updateNotifiable($user_id, $dev_token, $notifiable)){
            echo "good";
        }
        else{
            echo "Server Error";
        }
    }
    
    public function addDevice(){
        $user_id = $this->input->post('uid');
        $dev_type = $this->input->post('device');
        $dev_token = $this->input->post('devtoken');
        $notifiable = $this->input->post('notifiable');
        
        if ($user_id == null || $dev_token == null || $dev_type == null){
            echo "Null inputs"; // Test output
            return;
        }
        
        $this->load->model('user_devices');
        
        $this->user_devices->deleteDevice($dev_token);
        
        if ($this->user_devices->addDevice($user_id, $dev_type, $dev_token, $notifiable)){
            echo "good";
        }
        else{
            echo "Server Error";
        }
    }
    
    public function confirmCredentials(){
        $username = $this->input->post('user');
        $password = $this->input->post('pass');
        $dev_token = $this->input->post('devtoken');
        
        $password = $password; //Hash the password some way
        
        $this->load->model('user_devices');
        $this->load->model('users');
        
        $user = $this->users->authenticate($username, $password);
        if ($user == null){
            echo "fail";
            return;
        }
        
        echo "good";
    }
    
    public function logout(){
        $dev_token = $this->input->post('devtoken');
        
        $this->load->model('user_devices');
        $this->user_devices->deleteDevice($dev_token);
    }
        
    public function changePassword(){
        $oldpass = $this->input->post('oldpass');
        $newpass = $this->input->post('newpass');
        $user_id = $this->input->post('user_id');
        
        $this->load->model('users');
        if ($this->users->updatePassword($user_id, $oldpass, $newpass)){
            echo "good";
        }
        else{
            echo "fail";
        }
    }
    
    public function todaysMeals(){
        $user_id = $this->input->post('user_id');
        
        $this->load->model('mealtimes');
        $this->load->model('defaults');
        $this->load->model('mealtime_meals');
        $this->load->library('Xml_writer');
                
        $meals = $this->mealtimes->getMealsYMD(date('Y'), date('n'), date('j'));
       
        $xml = new Xml_writer;
        $xml->setRootName('data');
        $xml->initiate();

        foreach ($meals->result() as $result) {
            $xml->startBranch('meal');
                $xml->addNode('id', $result->mealtime_meals_id);
                $xml->addNode('name', $result->meal_title);
                $xml->addNode('description', $result->meal_description);
                if ($this->mealtime_meals->getVoted($user_id,$result->mealtime_meals_id)){
                    $xml->addNode('voted', 1);
                }
                if ($this->mealtime_meals->getOrdered($user_id,$result->mealtime_meals_id)){
                    $xml->addNode('ordered', 1);
                }
                if ($result->mealtime_orderable && $this->defaults->ordersAllowed()){
                    $xml->addNode('orderable', 1);
                }
                else{
                    $xml->addNode('orderable', 0);
                }
            $xml->endBranch();
        }

        $xml->getXml(true);
        
    }
    
    public function feedback(){
        $feedback = $this->input->post("content");
        $id = $this->input->post("id");
        
        $this->load->model('feedbacks');
        if ($this->feedbacks->insertFeedback($id, filter_profanity($feedback))){
            //echo "good";
            echo "Feedback submitted"; //Legacy code
        }
        else{
            //echo "fail";
            echo "Database error"; //Legacy code
        }
    }
    
    
    public function cancelVote(){
        $user_id = $this->input->post('user_id');
        
        $this->load->model('mealtimes');
        $this->load->model('user_votes');
        
        $mealtime = $this->mealtimes->getMealID();
        
        $servetime = date("H:i:s", strtotime($mealtime->mealtime_servetime)); 
        $currentTime = date("H:i:s", time());
        
        if ($servetime < $currentTime){
            echo "Sorry, unable to cancel vote after the voting period has ended.";
            return;
        }
        
        if ($this->user_votes->deleteVote($user_id, $mealtime->mealtime_id)){
            echo "good";
        }
        else{
            echo "fail";
        }
    }
    
    public function cancelOrder(){
        $user_id = $this->input->post('user_id');
        
        $this->load->model('mealtimes');
        $this->load->model('user_orders');
        
        $mealtime = $this->mealtimes->getMealID();
        
        $cutoff = date("H:i:s", strtotime($mealtime->mealtime_cutoff)); 
        $currentTime = date("H:i:s", time());
        
        if ($cutoff < $currentTime){
            echo "Sorry, unable to cancel your order after the ordering period has ended.";
            return;
        }
        
        if ($this->user_orders->deleteOrder($user_id, $mealtime->mealtime_id)){
            echo "good";
        }
        else{
            echo "fail";
        }
    }
    
    
}